<template>
	<div>
		<a-upload v-model:file-list="fileList" list-type="picture-card" name="upload" :action="uploadAction" :headers="uploadHeaders" :show-upload-list="false" :before-upload="beforeUpload" :data="uploadData" @change="changeUpload">
			<template v-if="thumb">
				<img :src="thumb" style="width:100%" />
				<div class="icon" @click.stop.prevent>
					<a-popconfirm title="确定要移除图片吗？" ok-text="是" cancel-text="否" @confirm="removeThumb">
						<delete-outlined />
					</a-popconfirm>
				</div>
			</template>

			<div v-else>
				<loading-outlined v-if="loading"></loading-outlined>
				<plus-outlined v-else></plus-outlined>
				<div class="ant-upload-text">上传</div>
			</div>
		</a-upload>
	</div>
</template>

<script setup>
import { getCurrentInstance, ref, computed } from "vue";
import { LoadingOutlined, PlusOutlined, DeleteOutlined } from "@ant-design/icons-vue";

import { post } from "../utils";
import { baseURL } from "../utils/request";

const props = defineProps({
	value: {
		type: String,
		required: true,
		default: ""
	}
});

const { proxy } = getCurrentInstance();

const loading = ref(false);
const fileList = ref([]);

const thumb = computed(() => props.value?.split(",")[0]);

/*
const thumb = ref();
watch(
	() => props.value,
	value => {
		thumb.value = value;
	},
	{ immediate: true, deep: true }
);
*/

const uploadData = ref();
const uploadAction = ref();
const uploadHeaders = ref({
	"X-Requested-With": null
});

const ossParams = ref({});

const beforeUpload = async file => {
	if (!/^image\//.test(file.type)) {
		proxy.$message.error("图片格式不符合要求");
		return false;
	} else if (file.size / 1024 / 1024 > 2) {
		proxy.$message.error("图片大小不能超过2MB");
		return false;
	}

	uploadAction.value = `${baseURL}/util/upload`;
	uploadData.value = {
		token: proxy.$cookies.get("token")
	};

	/*
	const { host, accessid, signature, policy, key } = (ossParams.value = await post(`${baseURL}/util/oss?token=${proxy.$cookies.get("token")}`, { name: file.name }));
	uploadAction.value = host;
	uploadData.value = {
		OSSAccessKeyId: accessid,
		policy,
		signature,
		key
	};
	*/

	return true;
};

const emit = defineEmits(["update:value"]);

const changeUpload = ({ file }) => {
	if (file.status === "done") {
		//thumb.value = file.response.data.url;
		emit("update:value", file.response.data.url);
		//emit("update:value", `${ossParams.value.url}`);
	}
};

const removeThumb = e => {
	emit("update:value", "");
};
</script>

<style scoped lang="scss">
:deep(.ant-upload) {
	position: relative;

	.icon {
		position: absolute;
		right: 0;
		top: 0;

		font-size: 16px;
		color: #ff4d4f;
		width: 24px;
		height: 24px;
		display: flex;
		justify-content: center;
		align-items: center;
		background: rgba(255, 255, 255, 0.8);
		border-radius: 6px;

		opacity: 0;
	}
	&:hover {
		.icon {
			opacity: 1;
		}
	}
}
</style>